-module(element_code).
-include_lib("nitrogen/include/wf.inc").
-include("src/api/useful.hrl").
-compile(export_all).

						% To handle element_code functions, a module MUST export the exec(Fun, Arg) -> Fun(Arg). function

render(code_run, Caller) -> 
    Body = [
	    #p{},
	    #textarea{id=cr_code, style="width: 100%;"},
	    #button{text="Lancer l'évaluation", actions=helper:act(?MODULE, {run_code, Caller})},

	    #p{},
	    #table { style="width: 100%;", 
		     rows=[
			   #tablerow { cells=[
					      #tableheader { style="width: 100%;", text="Output" }
					     ]},
			   #tablerow { cells=[
					      #tablecell { id=cr_output }
					     ]}
			  ]}
	   ],
    wf:render(Body);

render(code_toplevel, Caller) ->
    Body = [
	    #p{},
	    	    #table { style="width: 100%;", 
		     rows=[
			   #tablerow { cells=[
					      #tableheader { style="width: 10%;" },
					      #tableheader { style="width: 90%;" }
					     ]},
			   #tablerow { cells=[
					      #tablecell { id=ct_from },
					      #tablecell { id=ct_output }
					     ]}
			  ]},
	    
	    #p{},
	    #textbox{id=ct_code, style="width:100%;"},
	    #button{text="Evaluer", actions=helper:act(?MODULE, {eval_code, Caller})}
	    ],
    wf:render(Body);

render(_, _) ->
    " :) ".

event({run_code, Caller}) ->
    [Code] = wf:q(cr_code),
    Output = helper:runhertz(?HERTZ_LANG_PATH, Code),

    Caller:exec(fun(X) -> wf:insert_top(cr_output, #panel{body=X, actions=#show{effect=pulsate, options=[{times, 1}]} }) end, Output),
    ok;

event({eval_code, Caller}) ->
    [Code] = wf:q(ct_code),

    hertz_top ! {talk, self(), helper:get_session_pid(), Code},
    Output = receive
	{ok, Out} -> Out;
	Other -> io:format("Other : ~w~n", [Other]), ""
    end,
    
   % Output = helper:say_htoplevel(Code),
    io:format("Output : ~s~n", [Output]),

    Caller:exec(fun(_) -> wf:insert_bottom(ct_from, #panel{body="# ", actions=#show{effect=pulsate, options=[{times, 1}]} }) end, []),   
    Caller:exec(fun(X) -> wf:insert_bottom(ct_output, #panel{body=X, actions=#show{effect=pulsate, options=[{times, 1}]} }) end, Code),

    Caller:exec(fun(_) -> wf:insert_bottom(ct_from, #panel{body="> ", actions=#show{effect=pulsate, options=[{times, 1}]} }) end, []),  
    Caller:exec(fun(X) -> wf:insert_bottom(ct_output, #panel{body=X, actions=#show{effect=pulsate, options=[{times, 1}]} }) end, Output);

event(_) ->
    ok.

